package net.chasing.androidbaseconfig.util.glide;

import android.content.Context;
import android.graphics.drawable.Drawable;

import com.bumptech.glide.Glide;
import com.bumptech.glide.gifdecoder.GifDecoder;
import com.bumptech.glide.load.resource.gif.GifDrawable;

import net.chasing.androidbaseconfig.util.ReflectUtils;
import net.chasing.androidbaseconfig.util.thread.ComparableRunnable;
import net.chasing.androidbaseconfig.util.thread.ThreadPoolUtils;

public class GlideUtils {
    public static void clear(final Context context) {
        //清除Glide缓存
        ThreadPoolUtils.getInstance().executeOnMainThread(()-> Glide.get(context).clearMemory());
        ThreadPoolUtils.getInstance().execute(new ComparableRunnable() {
            @Override
            public void run() {
                //清理磁盘缓存
                Glide.get(context).clearDiskCache();
            }
        });
    }

    //获取gif图片的时长
    public static int getGifDrawableAnimTime(GifDrawable resource) {
        int mMenuAnimTime = 0;
        // 计算动画时长
        Drawable.ConstantState state = resource.getConstantState();
        if (state != null) {
            //不能混淆GifFrameLoader和GifState类
            Object gifFrameLoader = ReflectUtils.getValue(state, "frameLoader");
            if (gifFrameLoader != null) {
                Object decoder = ReflectUtils.getValue(gifFrameLoader, "gifDecoder");
                if (decoder instanceof GifDecoder) {
                    for (int i = 0; i < resource.getFrameCount(); i++) {
                        mMenuAnimTime += ((GifDecoder) decoder).getDelay(i);
                    }
                }
            }
        }
        return mMenuAnimTime;
    }
}
